package com.amkai.aes.webservice.binary.objecthandler.registration;

import java.io.Serializable;
import java.util.List;

import com.amkai.aes.aescommon.ledger.calculations.BalanceValues;
import com.amkai.aes.aescommon.ledger.calculations.LedgerBalance;
import com.amkai.aes.aescommon.service.binary.job.registration.PatientBalanceCheckingJob;
import com.amkai.aes.generatedbeans.billingledger.Charge;
import com.amkai.aes.generatedbeans.billingledger.Entry;
import com.amkai.aes.generatedbeans.billingledger.UnassignedPayment;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;

public class PatientBalanceCheckingHandler implements JobObjectHandler<PatientBalanceCheckingJob, Serializable, Boolean> {

	@Override
	public Boolean process(PatientBalanceCheckingJob job, Serializable object) throws Exception {
		boolean canDeactivate = true;
		
		SessionManager sm = SiteManager.Start();
		// KKORNEL: AES-3961
		if (hasBalance(sm, job.getPatientId(), job.getModuleDepartment().getId(), Charge.class) || 
			hasBalance(sm, job.getPatientId(), job.getModuleDepartment().getId(), UnassignedPayment.class)) {
			canDeactivate = false;
		}
		
		sm.closeSession();
		
		return canDeactivate;
	}

	// KKORNEL: AES-3961
	@SuppressWarnings("unchecked")
	private <LedgerEntry extends Entry> boolean hasBalance(SessionManager sm, Long patientId, Long departmentId, Class<LedgerEntry> clazz) {
		List<Entry> entryList = sm.execute("FROM "+clazz.getCanonicalName()+" ch WHERE (ch.patient = :patientid) and (ch.batch.period.baseOrganization.id = :boId)")
		                       .setLong("patientid", patientId).setLong("boId", departmentId).list();		
		BalanceValues bv = LedgerBalance.Calculate(entryList);
		if (bv.getPatientBalance() != 0.0d || bv.getInsuranceBalance() != 0.0d || bv.getAccountBalance() != 0.0d ) {
			return true;
		}
		
		return false;
	}
}
